<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace controller;

use think\Controller;
use think\Db;
use think\db\Query;
use think\Request;
use service\DataService;
use service\ToolsService;
use app\client\model\NodeModel;

/**
 * 基础控制器
 *
 * @package controller
 */
class BasicClient extends Controller {

    /**
     * 页面标题
     * @var string
     */
    protected $title;

    /**
     * 默认操作数据表
     * @var string
     */
    protected $table;

    /**
     * 默认检查用户登录状态
     * @var bool
     */
    protected $checkLogin = true;

    /**
     * 默认检查节点访问权限
     * @var bool
     */
    protected $checkAuth = true;

    protected $spm;

    protected $user;

    public $conSU;
    public $SU;
    public $AR;
    public $SystemUser = 'SystemUser';
    public $Area = 'Area';
    public $Nation = 'Nation';
    public $Disease = 'Disease';
    public $Patient = 'Patient';
    public $Characteristic = 'Characteristic';

    /**
     * 初始化方法
     */
    public function _initialize() {
        parent::_initialize();
        $this->conSU = config('dbx.SU');
        $this->SU = Db::connect($this->conSU)->name($this->SystemUser);
        $this->AR = Db::connect($this->conSU)->name($this->Area);

        //民族+疾病
        $this->nation = Db::connect($this->conSU)->name($this->Nation);
        $this->nationList = $this->nation->where(['status' => 1, 'is_deleted' => 0])->order('sort asc')->select();
        $this->assign('nationList', $this->nationList);
        $this->disease = Db::connect($this->conSU)->name($this->Disease);
        $this->diseaseList = $this->disease->where(['status' => 1, 'is_deleted' => 0])->order('sort asc')->select();
        $this->assign('diseaseList', $this->diseaseList);

        $this->aid = session('user.aid') ? session('user.aid') : 1;   
        $this->areas = $this->AR->order('area_id asc')->select();
        $this->aids = ToolsService::getArrSubIds($this->areas, $this->aid ,'area_id','area_parent_id');//当前区域下地区Ids
        $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
        $this->assign('areaList', $areaList);
        // halt($areaList);
        
        //多选地区
        $this->newareas = $this->AR->where(['area_open' => 1, 'area_parent_id' => 0])->field('area_id as value, area_name as name')->order('area_sort asc')->select();
        // $newareas = ToolsService::arr2subs($this->newareas);
        // $this->assign('newareas', $newareas);
        
        $this->newnations = Db::name('Nation')->where(['status' => 1, 'is_deleted' => 0])->field('id as value, title as name')->order('sort asc')->select();
        $this->assign('newnations', $this->newnations);
        
        $this->newdiseases = Db::name('Disease')->where(['status' => 1, 'is_deleted' => 0])->field('id as value, title as name')->order('sort asc')->select();
        $this->assign('newdiseases', $this->newdiseases);
        // halt($this->newnations);
        
        $usergroup = config('dbx.member_auth');
        $this->assign('rlist',$usergroup);

        $adminUser = session('user');
        $code = $this->request->param('code');
        list($module, $controller, $action) = [$this->request->module(), $this->request->controller(), $this->request->action()];

        // if ((in_array(1, explode(',', $adminUser['authorize'])) || in_array(4, explode(',', $adminUser['authorize']))) && $code) {
        if ($code) {
            session('c_user', null);
            // 系统管理员 有权限查看系统信息
            // $code = $this->request->param('code');
            $formed_code  = decrypt(base64_decode($code), get_auth_key());     
            // halt($formed_code);   
            //code验证
            if(!$code || !$formed_code){
                flash('error', '非法请求!');
                $this->redirect(url('@client/login'));
            }

            $user = Db::connect($this->conSU)->name('Client')->where('id', $formed_code)->find();
            if(empty($user['admin_id'])){
                flash('error', '未绑定管理员!');
                $this->redirect('@client/login');
            }
            $member = Db::connect($this->conSU)->name('Member')->where('id', $user['admin_id'])->find();
            // halt($member);
            
            if($member['status'] == 0){
                flash('error', '用户已被禁用!');
                $this->redirect('@client/login');
            }

            //远程更新auth_key
            Db::connect($this->conSU)->name('SystemConfig')->where('name', 'auth_key')->update(['value' => md5(uniqid(md5(microtime(true)),true))]);

            session('c_user', $user);
            // halt(session('c_user'));
            !empty($user['authorize']) && NodeModel::applyAuthNode();
            
            //登录成功 更新登录时间记录
            $update = array('login_num'=>array('exp','login_num+1'),'login_at'=>time());
            Db::connect($this->conSU)->name('Member')->where(array('id'=>$user['id']))->update($update);
            
            $this->redirect('@client');
        }else {
            // 用户登录状态检查
            if (($this->checkLogin || $this->checkAuth) && !session('c_user')) {
                $this->redirect('@client/login');
            }

        }

        // 获取登陆用户信息
        $user = session('c_user');
        $this->assign('user', $user);

        $this->user = $user;
        $this->uid = $this->user['id'];

        // 初始化赋值常用变量
        $this->assign('classuri', strtolower("{$module}/{$controller}"));

        // 初始化url spm值
        $this->spm = $this->request->param('spm');
        $this->assign('spm', $this->spm);
    }

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        // 判断登录状态 直接跳转到登录页面
        if (request()->path() == 'admin' && !session('user')) {
            $this->redirect(url('@admin/login'));
        }
    }

    /**
     * 表单默认操作
     * @param Query $db 数据库查询对象
     * @param string $tpl 显示模板名字
     * @param string $pk 更新主键规则
     * @param array $where 查询规则
     * @param array $data 扩展数据
     * @return array|string
     */
    protected function _form($dbQuery = null, $tplFile = '', $pkField = '', $where = [], $extendData = [])
    {
        $db = is_null($dbQuery) ? Db::name($this->table) : (is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery);
        $pk = empty($pkField) ? ($db->getPk() ? $db->getPk() : 'id') : $pkField;
        $pkValue = $this->request->request($pk, isset($where[$pk]) ? $where[$pk] : (isset($extendData[$pk]) ? $extendData[$pk] : null));
        // 非POST请求, 获取数据并显示表单页面
        if (!$this->request->isPost()) {
            $vo = ($pkValue !== null) ? array_merge((array)$db->where($pk, $pkValue)->where($where)->find(), $extendData) : $extendData;
            if (false !== $this->_callback('_form_filter', $vo)) {
                empty($this->title) || $this->assign('title', $this->title);
                return $this->fetch($tplFile, ['vo' => $vo]);
            }
            return $vo;
        }
        // POST请求, 数据自动存库
        $data = array_merge($this->request->post(), $extendData);
        if (false !== $this->_callback('_form_filter', $data)) {
            $result = DataService::save($db, $data, $pk, $where);
            if (false !== $this->_callback('_form_result', $result)) {
                if ($result !== false) {
                    $this->success('恭喜, 数据保存成功!', '');
                }
                $this->error('数据保存失败, 请稍候再试!');
            }
        }
    }

    /**
     * 列表集成处理方法
     * @param Query $db 数据库查询对象
     * @param bool $is_page 是启用分页
     * @param bool $is_display 是否直接输出显示
     * @param bool $total 总记录数
     * @return array|string
     */
    protected function _list($dbQuery = null, $isPage = true, $isDisplay = true, $total = false, $result = [], $pkField = 'id', $sortField = 'sort')
    {
        $db = is_null($dbQuery) ? Db::name($this->table) : (is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery);
        // 列表排序默认处理
        if ($this->request->isPost() && $this->request->post('action') === 'resort') {
            $data = $this->request->post();
            unset($data['action']);
            foreach ($data as $key => &$value) {
                if (false === $db->where($pkField, intval(ltrim($key, '_')))->setField($sortField, $value)) {
                    $this->error('列表排序失败, 请稍候再试');
                }
            }
            $this->success('列表排序成功, 正在刷新列表', '');
        }
        // 列表数据查询与显示
        if (null === $db->getOptions('order')) {
            $fields = $db->getTableFields($db->getTable());
            in_array($sortField, $fields) && $db->order($sortField.' asc');
        }
        if ($isPage) {
            $rows = intval($this->request->get('rows', cookie('rows')));
            cookie('rows', $rows >= 10 ? $rows : 20);
            $page = $db->paginate($rows, $total, ['query' => $this->request->get('', '', 'urlencode')]);
            list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
            list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())];
        } else {
            $result['list'] = $db->select();
        }
        !empty($this->title) && $this->assign('title', $this->title);
        if (false !== $this->_callback('_data_filter', $result['list']) && $isDisplay) {
//            !empty($this->title) && $this->assign('title', $this->title);
            return $this->fetch('', $result);
        }
        return $result;
    }

    /**
     * 列表ajax获取数据方法
     * @param null $db 数据库查询对象
     * @param int $page 页码
     * @param int $size 数量
     * @return \think\response\Json
     */
    protected function _ajaxData($db = null,$searchArray = [], $page = 1, $size = 20) {

        if (is_null($db)) {
            $db = Db::name($this->table);
        } elseif (is_string($db)) {
            $db = Db::name($db);
        }

        $page = $this->request->param('page', $page);
        $size = $this->request->param('limit', $size);

        $get = $this->request->get();
        // 搜索
        if ($searchArray) {
            $keyArr = !empty($get['key']) ? $get['key'] : [];
            foreach ($searchArray as $key) {

                if (isset($keyArr[$key]) && $keyArr[$key] !== '') {
                    $db->where($key, 'like', "%{$keyArr[$key]}%");
                }
            }
        }

        $data = $db->page($page, $size)->select();
        $count = $db->count();

        $result = [
            'code' => 0,
            'count' => $count,
            'data' => $data,
            'msg' => '获取数据成功'
        ];

        return json($result);
    }

    /**
     * 当前对象回调成员方法
     * @param string $method
     * @param array $data
     * @return bool
     */
    protected function _callback($method, &$data) {
        foreach ([$method, "_" . $this->request->action() . "{$method}"] as $method) {
            if (method_exists($this, $method) && false === $this->$method($data)) {
                return false;
            }
        }
        return true;
    }

    /**
     * ajax 返回
     * @param int $result
     * @param array $data
     * @param string $msg
     * @return mixed
     */
    protected function response($result = 0, $data = [], $msg = ''){
        return json(['result' => $result, 'data' => $data, 'msg' => $msg]);
    }
    
     /**
     * json输出地址数组 原data/resource/js/area_array.js
     */
    public function _json_area()
    {
        $get=$this->request->get();
        $get['src'] = $get['src'] != 'db' ? 'cache' : 'db';
        echo $get['callback'] . '(' . json_encode(model('area')->getAreaArrayForJson($get['src'])) . ')';
    }
    
    /**
     * json输出地址数组
     */
    public function _json_area_show()
    {
        $area_info['text'] = model('area')->getTopAreaName(intval(input('get.area_id')));
        echo input('get.callback').'('.json_encode($area_info).')';
    }
    
    //地区节点（带上下级）
    public function _getAreaTrees($table = 'Area', $where = ['area_open' => 1]) {
        $_menus = Db::name($table)->where($where)->order('area_sort asc,area_id asc')->select();

        $menus = ToolsService::arr2table($_menus,'area_id','area_parent_id');
        foreach ($menus as $key => &$menu) {

            if (substr_count($menu['path'], '-') > 4) {
                unset($menus[$key]);
                continue;
            }
            if (isset($vo['area_parent_id'])) {
                $current_path = "-{$vo['area_parent_id']}-{$vo['area_id']}";
                if ($vo['area_parent_id'] !== '' && (stripos("{$menu['path']}-", "{$current_path}-") !== false || $menu['path'] === $current_path)) {
                    unset($menus[$key]);
                }
            }
        }
        return $menus;
    }
    
    //站点模板节点（带上下级）
    public function _getTempTrees() {
        $_menus = Db::name($this->tempTreeTable)->select();

        $menus = ToolsService::arr2table($_menus,'id');
        foreach ($menus as $key => &$menu) {

            if (substr_count($menu['path'], '-') > 3) {
                unset($menus[$key]);
                continue;
            }
            // if (isset($vo['area_parent_id'])) {
            //     $current_path = "-{$vo['area_parent_id']}-{$vo['id']}";
            //     if ($vo['area_parent_id'] !== '' && (stripos("{$menu['path']}-", "{$current_path}-") !== false || $menu['path'] === $current_path)) {
            //         unset($menus[$key]);
            //     }
            // }
        }
        return $menus;
    }


}
